<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC
 * Date: 10/3/13
 * Time: 2:20 PM
 * To change this template use File | Settings | File Templates.
 */

class WidgetTopCategoriesPosition extends CWidget {
    public $categories, $position;

    public function init() {
        $category_position_cache = Yii::app()->cache->get('category_position_cache');
//        if ($category_position_cache == null || count($category_position_cache) == 0) {
            $positions = CategoryPosition::model()->findAll(array(
                'select' => 'cat_id,page',
                'condition' => 'position = :position',
                'order' => 'page ASC, t.order ASC ',
                'params' => array(':position' => $this->position)
            ));
            $arr_cat = array();
            $result = array();
            $num = 0;
            $index = 0;
            foreach ($positions as $key => $position) {
                $category = Category::model()->findByPk($position->cat_id);
                $subs = Category::model()->findAll(
                    array(
                        'select' => 'cat_name,cat_id',
                        'condition' => 'parent_id = :parent_id',
                        'limit' => 3,
                        'params' => array(':parent_id' => $category->cat_id)
                    )
                );
                if ($num == 2 || $key == count($positions) - 1) {
                    array_push($result, array('id' => $category->cat_id, 'name' => $category->cat_name, 'picture' => $category->image_path, 'subs' => $subs));
                    $arr_cat[$index] = $result;
                    $result = array();
                    $index++;
                    $num = 0;
                } else {
                    array_push($result, array('id' => $category->cat_id, 'name' => $category->cat_name, 'picture' => $category->image_path, 'subs' => $subs));
                    $num++;
                }
            }
//            Yii::app()->cache->set('category_position_cache', $arr_cat, 'category_position_cache_time');
//            $category_position_cache = Yii::app()->cache->get('category_position_cache');
//        }
        $this->categories = $arr_cat;
    }

    public function run() {
        return CWidget::render('widgetTopCategoriesPosition', array('model' => $this->categories, 'position' => $this->position));
    }
}